var flag = true;
layui.use(['form','table', 'layer'],
function() {
	$ = layui.jquery;
	var form = layui.form,
	layer = layui.layer;
    var table = layui.table;

	 //监听提交
	form.on('submit(add)',
	function(data) {
		if(flag)
		{
			flag = false;
			$("#signupForm").ajaxSubmit(function (message) {
				 console.log(message);
                 
                 if(message.code == 10001)
				 {
					layer.msg("执行成功", {
						icon: 6
					},
					function() {
						//关闭当前frame
						xadmin.close();
						// 可以对父窗口进行刷新 
						xadmin.father_reload();
					});
				 }else{
					layer.msg(message.msg, {
						icon: 5
					},
					function() {
						//关闭当前frame
						xadmin.close();
						// 可以对父窗口进行刷新 
						xadmin.father_reload();
					});
				 }
			});
		}else{
			layer.msg('正在提交。。。', {icon: 6});
		}
		return false;
	});

    	/*初始化表格*/
	window.tableInit = function()
	{  
        var params = {};
        params.sn = sn;
	  table.render({
		elem: '#dataTables-example'
		,url:'/shop/consult/consgoodslist.html'
		,where:params
		,method:'POST'
		,parseData: function(res){ //res 即为原始返回的数据
            //封装返回数据
			console.log(res);
			for (i in res.data) {
                    res.data[i]['is_stock'] = res.data[i].is_stock==0?'无货':'有货';
                    res.data[i]['reason'] = "<button type='button' class='layui-btn delGoods' gid='"+res.data[i].consult_goods_id+"'>取消</button>";
                    res.data[i]['reason'] += "<input type='hidden' name='gids[]' value='"+res.data[i].consult_goods_id+"'/>"; 
			}
			return {
			  "code": 10001, //解析接口状态
			  "msg": '', //解析提示文本
			  "count": res.total, //解析数据长度
			  "data": res.data //解析数据列表
			};
		}
		,cols: [[
		  {field:'consult_goods_id', title: '序号'}
          ,{field:'goods_name', title: '产品名称'}
		  ,{field:'category_name', title: '产品分类'}
		  ,{field:'cat_name', title: '产品子分类'}
		  ,{field:'brand_name', title: '品牌'}
		  ,{field:'marker', title: '型号'}
		  ,{field:'memory_name', title: '内存'}
		  ,{field:'attribute_name', title: '属性'}
		  ,{field:'colour_name', title: '颜色'}
		  ,{field:'is_stock', title: '是否有货'}
          ,{field:'reason', title: '操作'}
		]]
		,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
		  layout: ['prev', 'page', 'next', 'skip', 'count']
		}
		,response: {
			statusCode: 10001
		}
	  });
	}
	tableInit();
    //退货
    $('body').on('click', '.delGoods', function(){
        var get_this = $(this);
        parent.layer.confirm('你确定要取消吗?', function(){
            var params = {};
            params.id = get_this.attr('gid');
            $.ajax({
                type: "POST",
                url: "/shop/consult/delgoods.html",
                cache: false, //禁用缓存
                data: params, //传入组装的参数
                dataType: "json",
                success: function (result) {
                    if(result.code==10001){
                        tableInit();
                        parent.layer.msg('操作成功', {icon: 1});
                    }else{
                        parent.layer.msg(result.msg, {icon: 5});
                    }
                },
                error:function () {
                    parent.layer.msg('网络错误', {icon: 5});
                }
            })
        });
    });
    
    var input = document.getElementById("upgteimg");
    var showui = document.getElementById("showui");
    var result;
    var dataArr = []; // 储存所选图片的结果(文件名和base64数据)
    var fd; //FormData方式发送请求
    var showinput = document.getElementById("showinput");
    var oSubmit = document.getElementById("submit");
    var dateli, dateinput;
    if(typeof FileReader === 'undefined') {
        alert("抱歉，你的浏览器不支持 FileReader");
        input.setAttribute('disabled', 'disabled');
    } else {
        input.addEventListener('change', readFile, false);
    }
    function randomString(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        for(i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }
    function readFile() {
        fd = new FormData();
        var iLen = this.files.length;
        var index = 0;
        var currentReViewImgIndex = 0;
        for(var i = 0; i < iLen; i++) {
            if(!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)) {//判断上传文件格式
                return alert("上传的图片格式不正确，请重新选择");
            }
            var reader = new FileReader();
            reader.index = i;
            fd.append(i, this.files[i]);
            reader.readAsDataURL(this.files[i]); //转成base64
            reader.fileName = this.files[i].name;
            reader.files = this.files[i];
            reader.onload = function(e) {
                var imgMsg = {
                    name: randomString(5), //获取文件名
                    base64: this.result, //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里
                }
                dataArr.push(imgMsg);
                for(var j = 0; j < dataArr.length; j++) {
                    currentReViewImgIndex = j
                }
                result = '<div class="showdiv"><input type="hidden" name="imgs[]" value="' + this.result + '"/><img class="left" src="/static/css/img/Arrow_left.svg" /><img class="center" src="/static/css/img/delete.svg" /><img class="right" src="/static/css/img/Arrow_right.svg" /></div><img id="img' +currentReViewImgIndex+randomString(1)+randomString(2) +randomString(5) + '" class="showimg" src="' + this.result + '" />';
                var li = document.createElement('li');
                li.innerHTML = result;
                showui.appendChild(li);
                index++;
            }
        }
    }
    function onclickimg() {
        var dataArrlist = dataArr.length;
        var lilength = document.querySelectorAll('ul#showui li');
        for(var i = 0; i < lilength.length; i++) {
            lilength[i].getElementsByTagName('img')[0].onclick = function(num) {
                return function() {
                    if(num == 0) {} else {
                        var list = 0;
                        for(var j = 0; j < dataArr.length; j++) {
                            list = j
                        }
                        var up = num - 1;
                        dataArr.splice(up, 0, dataArr[num]);
                        dataArr.splice(num + 1, 1)
                        var lists = $("ul#showui li").length;
                        for(var j = 0; j < lists; j++) {
                            var usid = $("ul#showui li")[j].getElementsByTagName('img')[3];
                            $("#" +usid.id+ "").attr("src", dataArr[j].base64)
                        }
                    }
                }
            }(i)
            //删除图标
            lilength[i].getElementsByTagName('img')[1].onclick = function(num) {
                return function() {
                    if(dataArr.length == 1) {
                        dataArr = [];
                        $("ul#showui").html("")
                    } else {
                        $("ul#showui li:eq(" + num + ")").remove()
                        dataArr.splice(num, 1)
                    }

                }
            }(i)
            //右箭头图标
            lilength[i].getElementsByTagName('img')[2].onclick = function(num) {
                return function() {
                    var list = 0;
                    for(var j = 0; j < dataArr.length; j++) {
                        list = j
                    }
                    var datalist = list + 1;
                    dataArr.splice(datalist, 0, dataArr[num]);
                    dataArr.splice(num, 1)
                    var lists = $("ul#showui li").length;
                    for(var j = 0; j < lists; j++) {
                        var usid = $("ul#showui li")[j].getElementsByTagName('img')[3];
                        $("#" + usid.id + "").attr("src", dataArr[j].base64)
                    }

                }
            }(i)

        }
    }
    showui.addEventListener("click", function() {
					onclickimg();
				}, true);
    
});

function userAjax(obj,ty)
    {
        var params = {};
        params.sreach = $(obj).val();
        params.ty = ty;
        $.ajax({
            type: "POST",
            url: "/shop/addorder/eachuser.html",
            cache: false, //禁用缓存
            data: params, //传入组装的参数
            dataType: "json",
            success: function (result) {
                console.log(result)
                if(result.code==10001){
                    var str = '';
                    var urls = '';
                    for (i in result.option) {
                        urls = '/shop/addorder/userinfo/id/'+result.option[i]['user_id']+'.html';
                        str += '<span class="chakan span_nav" style="cursor:pointer;" onclick=\'xadmin.open("用户信息","'+urls+'",1000,600)\'>'+result.option[i]['user_sn']+'</span>&nbsp;&nbsp;';
                    }
                    $('#userdata').html(str);
                }else{
                    $('#userdata').html('');
                }
            },
            error:function () {
                parent.layer.msg('网络错误', {icon: 5});
            }
        })
    }